const express = require('express');
const pool = require('../pool');
//导入生成token的包 
const jwt =  require('jsonwebtoken');
//导入全局配置
const config = require('../config.js')
const router = express.Router();
//导入bcryptjs
const bcrypt = require('bcryptjs');
//待导入验证数据的中间件模块
const expressJoi =  require('@escook/express-joi');
//导入需要的验证规则对象
const {reg_form} = require('../schema/user');
const {reg_login} = require('../schema/user');
//注册新用户
router.post('/reguser',expressJoi(reg_form),(req,res)=>{
    //获取客户端提交到服务器的用户信息
    const userinfo = req.body;

    // if(!userinfo.username || !userinfo.phone || !userinfo){
    //     return res.send({status:1,msg:'用户名、账号、密码不能为空！'})
    // }
    
    //定义SQL语句，查询用户名是否被占用
    const sqlStr = 'select * from user where username=? or phone=?';
    pool.query(sqlStr,[userinfo.username,userinfo.phone],(err,r)=>{
        //执行SQL语句失败
        if(err){
            return res.cc(err);
        }

        if(r.length > 0){
            return res.send({status:1,msg:'用户名或账号已被占用!'});
        };
        //调用bcrypt.hashSync()对密码进行加密
        userinfo.password = bcrypt.hashSync(userinfo.password,10);

        //将用户信息存储到数据库中
        const sql = 'insert into user set ?';
        pool.query(sql,{username:userinfo.username,phone:userinfo.phone,password:userinfo.password},(err,r)=>{
            if(err){
                return res.cc(err);
            }

            if(r.affectedRows !== 1){
                return res.cc(err,'注册失败，请重试！');
            };

            res.send({code:200,msg:'注册成功'});
        });
       
    });
   
});

//登录
router.post('/login',expressJoi(reg_login),(req,res)=>{
    const userinfo = req.body;

    //执行sql语句查询用户的信息
    const sql = 'select * from user where phone=?';
    pool.query(sql,[userinfo.phone],(err,r)=>{
        if(err){
            //执行sql语句失败
            return res.cc(err)
        }

        if(r.length == 0){
            return res.cc('登录失败');
        }else{
            const compareR = bcrypt.compareSync(userinfo.password,r[0].password);
            console.log(compareR);
            if(!compareR) return res.cc('登录失败，密码错误');
            //提出用户信息中的密码和头像
            const user = {...r[0],password:'',user_pic:''};
            //对用户的信息进行加密，生成Token字符串
            const tokenStr = jwt.sign(user,config.jwtSecretKey,{expiresIn:config.expiresIn});
            
            //将token响应给客户端
            res.send({status:0,message:'登录 成功',token:'Bearer ' + tokenStr});
        }
    })
    
});

//修改密码
router.post('/uppwd',expressJoi(reg_login),(req,res)=>{
    const userinfo = req.body;
    const sql = 'select * from user where phone=?';
    pool.query(sql,[userinfo.phone],(err,r)=>{
        if(err){
            //执行sql语句失败
            return res.cc(err)
        }

        if(r.length == 0){
            return res.cc('账号或密码错误，请重试');
        }else{
            const compareR = bcrypt.compareSync(userinfo.password,r[0].password);
            if(!compareR) return res.cc('密码错误');
            //将新密码替换掉原密码
            pool.query('update user set password=? where phone=?',[userinfo.newpassword,userinfo.phone],(err,db)=>{

                if(err) return res.cc('修改失败，请重试！');

                if(db.affectedRows){
                    return res.send({status:0,message:'修改成功'});
                }
                res.cc('修改失败');
            })
            
            
            
           
        }
    })
});

//删除用户
router.post('/dluser',expressJoi(reg_login),(req,res)=>{
    const userinfo = req.body;
    
    pool.query('select * from user where phone = ? and password=?',[userinfo.phone],(err,r)=>{
        if(err){
            return res.cc(err);
        }
        pool.query('delete from user where phone=?',[userinfo],(err,r)=>{

        });
    });
});
//暴露用户路由
module.exports = router;